from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from user.contants import (GROUP_STUDENT,
                           GROUP_TEACHER, GROUP_SUPERVISOR)
from course.models import Course
from django.db.models import Q


class SidebarMixin(object):

    @property
    def sidebar_dic(self):
        user = self.request.user
        if user.is_in_group(GROUP_SUPERVISOR):
            courses = Course.objects.all()
        elif user.is_in_group(GROUP_STUDENT):
            courses = user.enrolling.all()
        else:
            courses = user.teaching.all()
        # print('courses', courses)
        sidebar_dic = {}
        for course in courses:
            title = course.slug
            if title not in sidebar_dic:
                sidebar_dic[title] = []
            sidebar_dic[title].append(course)
        return sidebar_dic


class PageinatorMixin(object):
    per_page = 10

    def paging(self, queryset):
        paginator = Paginator(queryset, self.per_page)
        p = self.request.GET.get('p')
        try:
            queryset = paginator.page(p)
        except PageNotAnInteger:
            queryset = paginator.page(1)
        except EmptyPage:
            queryset = paginator.page(paginator.num_pages)

        return queryset

    def filter_queryset(self, queryset):
        q = self.request.GET.get('q')
        if q:
            queryset = queryset.filter(
                Q(first_name__icontains=q) |
                Q(last_name__icontains=q) |
                Q(email__icontains=q) |
                Q(username__icontains=q)
            )
        return self.paging(queryset)


class UserCourseRelatedMixin(LoginRequiredMixin):
    '''
    check if user has relationship with the course
    set self.course_id before calling super.dispatch
    '''
    course_id = None
    course_slug = None

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return self.handle_no_permission()
        if self.course_slug:
            return super(UserCourseRelatedMixin, self).dispatch(
                request, *args, **kwargs)
        if self.course_id:
            course_id = self.course_id
        course = Course.objects.get(id=course_id)
        self.course_slug = course.slug
        if request.user.is_in_group(GROUP_SUPERVISOR):
            pass
        elif request.user.is_in_group(GROUP_STUDENT):
            if course not in request.user.enrolling.all():
                # print('student not enrolled yet')
                return self.handle_no_permission()
        elif request.user.is_in_group(GROUP_TEACHER):
            if course not in request.user.teaching.all():
                # print('teacher not assigned yet')
                return self.handle_no_permission()

        return super(UserCourseRelatedMixin, self).dispatch(
            request, *args, **kwargs)
